//
//  JYouLickView.m
//  HeadIndustry
//
//  Created by jun on 2017/8/30.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JYouLickView.h"
#import "JBaseCollectionViewCell.h"
#import "UICollectionView+JCollectionView.h"
#import "JCollectionHeadView.h"

@interface JYouLickView()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic , assign) CGFloat headHeight;
@property (nonatomic , assign) CGFloat cellWidth;
@property (nonatomic , strong) JCollectionHeadView *headerView;
@end

@implementation JYouLickView

// 注意const的位置
static NSString *const cellId = @"cellId";
static NSString *const headId = @"headId";


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];
        self.opaque = NO;
        _dataArr = [NSArray array];
        _cellWidth = (kWindowW - 15*3)/2.0;
        _headHeight = 200;
//        [self loadAdviceKindArr];

        [self setUpView];
        
        [self setUpCollectView];
    }
    return  self;
}

- (void)setUpView {
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWindowW, 40)];
    view.backgroundColor = [UIColor whiteColor];
    [self addSubview:view];
    
    YYLabel *titleLabel = [YYLabel new];
    titleLabel.left = 0;
    titleLabel.top = 5;
    titleLabel.size = CGSizeMake(kWindowW, 30);
    titleLabel.text = _titleStr;
    [titleLabel sizeToFit];
    titleLabel.top = 5;
    titleLabel.centerX = self.centerX;
    titleLabel.size = CGSizeMake(titleLabel.width, titleLabel.height);
    [view addSubview:titleLabel];
    _headTitleLabel = titleLabel;
    
    CALayer *imgLayer = [CALayer layer];
    imgLayer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"likely"].CGImage);
    imgLayer.right = titleLabel.left - 50;
    imgLayer.top = 15;
    imgLayer.size = CGSizeMake(20, 20);
    [view.layer addSublayer:imgLayer];
}

- (void)setUpCollectView {
    _collectView = [UICollectionView initWithCollectionView:CGRectMake(0, 0, kWindowW, self.height) withDelegate:self];
    
    _collectView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (self.dataArr.count == self.pageModel.pageIndex * self.pageModel.pageSize) {
            if (_refreshCellBlock) {
                _refreshCellBlock(_pageModel.pageIndex);
            }
            [_collectView.mj_footer endRefreshing];
        }
        else if (self.dataArr.count == 0)
        {
            if (_refreshCellBlock) {
                _refreshCellBlock(_pageModel.pageIndex - 1);
            }
            [_collectView.mj_footer endRefreshing];
        }
        else
        {
            [_collectView.mj_footer endRefreshingWithNoMoreData];
        }
        
    }];
    
    _collectView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
        if (_refreshBlock) {
            _refreshBlock();
        }
    }];
    
    [_collectView.mj_footer beginRefreshing];
    
    [self.collectView registerClass:[JCollectionHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headId];
    
    // 注册cell
    [self.collectView registerClass:[JBaseCollectionViewCell class] forCellWithReuseIdentifier:cellId];
    
    [self addSubview:_collectView];
}

//- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
//{
//    return 1;
//}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JBaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        cell.prodeutModel = _dataArr[indexPath.row];
    });
    
    return cell;
}

// 和UITableView类似，UICollectionView也可设置段头段尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
//    if (_isHeadView) {
        if([kind isEqualToString:UICollectionElementKindSectionHeader])
        {
            JCollectionHeadView *headerView = [_collectView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headId forIndexPath:indexPath];
            
            
            headerView.btnBlock = ^(JProductTypeModel *model) {
                if (_selHeadTypeBlock) {
                    _selHeadTypeBlock(model);
                }

            };
            
            headerView.killBtnBlock = ^(JKillProducModel *model) {
                if (_selHeadkillBlock) {
                    _selHeadkillBlock(model);
                }
            };
            headerView.getViewHeight = ^(CGFloat viewHeight) {
                _headHeight = viewHeight;
            };
            _headerView = headerView;
            return headerView;
        }

    return nil;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath
{
    
}


#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return (CGSize){_cellWidth,260};
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(15, 15, 15, 15);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15.f;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    NSLog(@"_headHeight====%.2f",_headHeight);
    return (CGSize){kWindowW, _headHeight};
}


//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
//{
//    return (CGSize){kWindowW,22};
//}




#pragma mark ---- UICollectionViewDelegate

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//// 点击高亮
//- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
//}

// 选中某item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_cellSelectBlock) {
        _cellSelectBlock(_dataArr[indexPath.row]);
    }
}

- (void)loadAdviceKindArr
{
    NSString *url = @"Categories/GetCategories";
    [JNetManager LoadKindAdviceImgUrl:url
                              success:^(id response) {
                                  if (response) {
                                      NSMutableArray *imgArr = (NSMutableArray *)response;
                                      _headHeight = 210 + ceilf(imgArr.count / 4.0 ) * (kWindowW/4.0 + 5) + 70;
                                      
                                      [_collectView reloadData];
                                  }
                              } failure:^(NSString *err) {
                                  [SVProgressHUD showErrorWithStatus:err];
                                  
                              }];
}


//// 长按某item，弹出copy和paste的菜单
//- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    return YES;
//}

//// 使copy和paste有效
//- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender
//{
//    if ([NSStringFromSelector(action) isEqualToString:@"copy:"] || [NSStringFromSelector(action) isEqualToString:@"paste:"])
//    {
//        return YES;
//    }
//
//    return NO;
//}
//
////
//- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender
//{
//    if([NSStringFromSelector(action) isEqualToString:@"copy:"])
//    {
//        //        NSLog(@"-------------执行拷贝-------------");
//        [_collectView performBatchUpdates:^{
////            [_section0Array removeObjectAtIndex:indexPath.row];
//            [_collectView deleteItemsAtIndexPaths:@[indexPath]];
//        } completion:nil];
//    }
//    else if([NSStringFromSelector(action) isEqualToString:@"paste:"])
//    {
//        NSLog(@"-------------执行粘贴-------------");
//    }
//}

- (void)setTitleStr:(NSString *)titleStr
{
    _titleStr = titleStr;
    _headTitleLabel.text = titleStr;
}

- (void)setDataArr:(NSArray *)dataArr
{
    _dataArr = dataArr;
    [_collectView reloadData];
}

- (CGFloat)getViewHeight
{
    if (_dataArr.count == 0) {
        return 0;
    }
    else
    {
        CGFloat height = 40 + 445 * _dataArr.count/2;
        return height;
    }
    
    return 0;
}

//- (void)loadKillView
//{
//    NSString *url = @"PopularKillApi/GetPopularKillProducts";
//    [JNetManager LoadKillProductImgUrl:url
//                               success:^(id response) {
//                                   if (response) {
//                                       
//                                       
//                                       NSMutableArray *imgArr = (NSMutableArray *)response;
//                                       
////                                       NSMutableArray *imgURLArr = [NSMutableArray array];
//                                       
//                                       
////                                       dispatch_async(dispatch_get_global_queue(0, 0), ^{
////                                           for (JKillProducModel *model in imgArr) {
////                                               [imgURLArr addObject:model.ImgUrl];
////                                           }
////                                           _killImgArr = [NSMutableArray arrayWithArray:imgURLArr];
////                                           
////                                           if (_killImgArr.count > 0) {
////                                               dispatch_async(dispatch_get_main_queue(), ^{
////                                                   [self setConfigBottomView:imgArr];
////                                                   
////                                               });
////                                           }
////                                       _headHeight = 210 + ceilf(imgArr.count / 4.0 ) * (kWindowW/4.0 + 5) + 70;
//                                       if (imgArr.count > 0) {
//                                           _headHeight = 210 + ceilf(imgArr.count / 4.0 ) * (kWindowW/4.0 + 5) + 70 + 160;
//                                           _headerView.killImgArr = imgArr;
//                                           [_collectView reloadData];
//                                       }
//                                       
//                                       
////                                       });
//                                   }
//                               } failure:^(NSString *err) {
//                                   [SVProgressHUD showErrorWithStatus:err];
//                               }];
//}
//
//- (void)loadAdviceKindArr
//{
//    NSString *url = @"Categories/GetCategories";
//    [JNetManager LoadKindAdviceImgUrl:url
//                              success:^(id response) {
//                                  if (response) {
//                                      NSMutableArray *imgArr = (NSMutableArray *)response;
//                                      
//                                      if (imgArr.count > 0) {
//                                          _headerView.kindNameArr = imgArr;
//                                          _headHeight = 210 + ceilf(imgArr.count / 4.0 ) * (kWindowW/4.0 + 5) + 70;
//                                          [_collectView reloadData];
//                                      }
//                                      
//                                      
////                                      dispatch_async(dispatch_get_global_queue(0, 0), ^{
////                                          
////                                          _kindNameArr = [NSArray arrayWithArray:imgArr];
////                                          CGFloat butWidth = kWindowW/4.0;
////                                          _minY = (butWidth + 5) * (_kindNameArr.count/4) + 210;
////                                        
////                                      });
//                                      
//                                  }
//                              } failure:^(NSString *err) {
//                                  [SVProgressHUD showErrorWithStatus:err];
//                                  
//                              }];
//}

@end
